package jsf.generator;

import java.util.HashMap;
import java.util.Map;


/**
 * Klasa koja vrsi konverziju iz srpske cirilice u latinicu 
 * i obratno 
 * 
 * @author abosancic
 * 
 */
public class CirLatConvertor {
	
     private static String []lat = {"a","b","c","d","e","f","g","h","i","j","k","l","lj","m","n","nj","o","p","r","s","t","u","v","š","đ","ž","z","dž","č","ć",
        "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","R","S","T","U","V","Š","Đ","Ž","Dž","Z","Nj","Lj","Č","Ć"};
        
     private static String []cir = {"а","б","ц","д","е","ф","г","х","и","ј","к","л","љ","м","н","њ","о","п","р","с","т","у","в","ш","ђ","ж","з","џ","ч","ћ"
        ,"А","Б","Ц","Д","Е","Ф","Г","Х","И","Ј","К","Л","М","Н","О","П","Р","С","Т","У","В","Ш","Ђ","Ж","Џ","З","Њ","Љ","Ч","Ћ"};
     
     private static Map cyrMapping = new HashMap<String,String>();
     private static Map latMapping = new HashMap<String,String>();      
     static {
        for (int i = 0; i < cir.length; i++) {
            latMapping.put(lat[i], cir[i]);
            cyrMapping.put(cir[i], lat[i]);
        }
     }
	
	 public static String cyrilicToLatin(String cyrilicText) {
		StringBuffer cyrBuffer = new StringBuffer(cyrilicText);
		StringBuffer latinBuffer = new StringBuffer();
                String lat = "";
		for (int i = 0; i < cyrBuffer.length(); i++)
                        if((lat = (String)cyrMapping.get(cyrBuffer.substring(i, i+1)))!= null)
			    latinBuffer.append(lat);
                        else
                            latinBuffer.append(cyrBuffer.substring(i, i+1));
		return latinBuffer.toString();
	}
	
	public static String latinToCyrilic(String latinText) {
		StringBuffer latBuffer = new StringBuffer(latinText);
		StringBuffer cyrBuffer = new StringBuffer();
	        String cir = ""; 
		for (int i=0; i < latBuffer.length(); i++) {
			String s = latBuffer.substring(i, i+1);			
			if (i < latBuffer.length() - 1 ) {
				char c = latBuffer.charAt(i+1);
				if (((s.equals("L") || s.equals("l")
					|| s.equals("N") || s.equals("n"))
					&& (c == 'J' || c == 'j'))) {
					s = s + 'j';
					i++;
				} else if ((s.equals("D") || s.equals("d")) 
						&& (c == '\u017D' || c == '\u017E')) {
					s = s + '\u017E';
					i++;
				}
			}
                             if((cir = (String)latMapping.get(s))!= null)
				cyrBuffer.append(cir);
                             else
                           	cyrBuffer.append(s.charAt(0));	
		}
		return cyrBuffer.toString();
	}
	
}
